package com.xiaohai.wx.weather.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.joda.time.LocalDate;
import org.testng.log4testng.Logger;

import com.xiaohai.wx.weather.dto.Weather;
import com.xiaohai.wx.weather.dto.messageOut.Article;
import com.xiaohai.wx.weather.dto.messageOut.MusicMessage;
import com.xiaohai.wx.weather.dto.messageOut.NewsMessage;
import com.xiaohai.wx.weather.dto.messageOut.TextMessage;
import com.xiaohai.wx.weather.service.Constants;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;


public class MessageUtil {

	public static final String RESP_MESSAGE_TYPE_TEXT = "text";

	public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

	public static final String RESP_MESSAGE_TYPE_NEWS = "news";

	public static final String REQ_MESSAGE_TYPE_TEXT = "text";

	public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

	public static final String REQ_MESSAGE_TYPE_LINK = "link";

	public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

	public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

	public static final String REQ_MESSAGE_TYPE_EVENT = "event";

	public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

	public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

	public static final String EVENT_TYPE_CLICK = "CLICK";
	
	private static Logger logger = Logger.getLogger(MessageUtil.class);
	

	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(HttpServletRequest request) throws IOException, DocumentException  {

		Map<String, String> map = new HashMap<String, String>();

		InputStream inputStream = request.getInputStream();

		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);

		Element root = document.getRootElement();

		List<Element> elementList = root.elements();

		for (Element e : elementList)
			map.put(e.getName(), e.getText());

		inputStream.close();
		inputStream = null;

		return map;
	}
	
	public static Map<String, String> parseXML(String xmlStr) throws DocumentException{
		
		Map<String, String> map = new HashMap<String, String>();

		SAXReader reader = new SAXReader();
		Document document = reader.read(new ByteArrayInputStream(xmlStr.getBytes()));

		Element root = document.getRootElement();

		List<Element> elementList = root.elements();

		for (Element e : elementList)
			map.put(e.getName(), e.getText());

		return map;
	}


	public static String textMessageToXml(TextMessage textMessage) {
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}


	public static String musicMessageToXml(MusicMessage musicMessage) {
		xstream.alias("xml", musicMessage.getClass());
		return xstream.toXML(musicMessage);
	}

	public static String newsMessageToXml(NewsMessage newsMessage) {
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new Article().getClass());
		return xstream.toXML(newsMessage);
	}
	
	public static Weather getWeatherFromXmlUrl(String urlStr){
		try{
			SAXReader reader = new SAXReader();
			reader.setEncoding("UTF-8");
			URL url = new URL(urlStr);
						
			Document document = reader.read(url);
			Element profiles = document.getRootElement();
			Element weatherEle = profiles.element("Weather");
			if (weatherEle==null){
				return null;
			}
			String tempHigh = weatherEle.element("temperature1").getText();
			String tempLow = weatherEle.element("temperature2").getText();
			String status1 = weatherEle.element("status1").getText();
			String status2 = weatherEle.element("status2").getText();
			String windDirection1 = weatherEle.element("direction1").getText();
			String windDirection2 = weatherEle.element("direction2").getText();
			String windPower1 = weatherEle.element("power1").getText();
			String windPower2 = weatherEle.element("power2").getText();
			String chy_shuoming = weatherEle.element("chy_shuoming").getText();
			String xcz_s = weatherEle.element("xcz_s").getText();
			String zwx_s = weatherEle.element("zwx_s").getText();
			zwx_s = zwx_s.replace("紫外线", "");
			String savedate_weather = weatherEle.element("savedate_weather").getText();
			
			if(StringUtils.isBlank(tempLow) || StringUtils.isBlank(tempHigh) || StringUtils.isBlank(windDirection1)
					|| StringUtils.isBlank(windPower1) || StringUtils.isBlank(status1) ){
				return null;
			}
			
			Weather weather = new Weather();
			
			weather.setDate(LocalDate.parse(savedate_weather));
			weather.setHighTemp(tempHigh);
			weather.setLowTemp(tempLow);
			weather.setIndex_dress(chy_shuoming);
			if(StringUtils.isNotBlank(status2) && !status1.equals(status2)){
				status1 = status1 +"转"+ status2;
			}
			weather.setWeather(status1);
			String wind1 = "";
			if(windDirection1.equals("无持续风向") || windPower1.equals("≤3")){
				wind1 = "微风";
			}else{
				wind1 = windDirection1 + windPower1 +"级";
			}
			
			String wind2 = "";
			if(windDirection2.equals("无持续风向") || windPower2.equals("≤3")){
				wind2 = "微风";
			}else{
				wind2 = windDirection2 + windPower2 +"级";
			}
			
			if(!wind2.equals(wind1) && !wind2.equals("")){
				if(wind1.equals("微风") || wind2.equals("微风") ){
					wind1 = wind1 + "转" + wind2;
				}else{
					if(windDirection1.equals(windDirection2)){
						wind1 = wind1 + "转" + windPower2 + "级";
					}else{
						wind1 = wind1 + "转" + wind2;
					}
				}
			}
			
			logger.debug("wind: "+ wind1);
			weather.setWind(wind1);
			//weather.setIndex_dress(chy_shuoming);
			if(!"暂无".equals(zwx_s)){
				weather.setIndex_uv(zwx_s);
			}
			if(!"暂无".equals(xcz_s)){
				weather.setIndex_xc(xcz_s);
			}
			
			return weather;
			
		}catch(IOException ioe){
			ioe.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void main(String[] args){
		
		Weather weather = MessageUtil.getWeatherFromXmlUrl("http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0");
		System.out.println(weather.toString());
	}
	
	public static String getTodayWeatherStr(List<Weather> list, String cityName){
		StringBuilder content = new StringBuilder();
		
		if(list == null || list.size()==0){
			return "";
		}
		
		content.append("=="+ cityName + " 今日天气=="+ "\n");
		Weather firstOne = list.get(0);
		String temp = firstOne.getLowTemp() + "~" + firstOne.getHighTemp() + Constants.degree;
		
		content.append("* "+ temp + "\n");
		content.append("* "+ firstOne.getWeather()+ "\n");
		content.append("* "+ firstOne.getWind()+ "\n");
		content.append("* 紫外线"+ firstOne.getIndex_uv()+ "\n");
		
		if(StringUtils.isNotBlank(firstOne.getAir_quality())){
			
			String note = Constants.airQualityNote.get(firstOne.getAir_quality());
			if(StringUtils.isNotBlank(note)){
				content.append("* "+ note + "\n");
			}
		}
		
		if(StringUtils.isNotBlank(firstOne.getTempChange())){
			content.append("* "+ firstOne.getTempChange() + "\n");
		}
		
		String xc = firstOne.getIndex_xc();
		if(StringUtils.isNotBlank(xc)){	
			if(xc.contains("。") && !xc.endsWith("。")){
				xc = xc.substring(xc.lastIndexOf("。")+1, xc.length());
				
			}else{
				xc = xc.substring(xc.lastIndexOf("，")+1, xc.length());
			}
			content.append("* "+ xc + "\n");
		}
		
		return content.toString();

	}
	
	public static String getTomorrowWeatherStr(List<Weather> list, String cityName){
		StringBuilder content = new StringBuilder();
		
		if(list == null || list.size()==0 || list.size() ==1){
			return "";
		}
		
		content.append("=="+ cityName + " 明日天气=="+ "\n");
		Weather tomorrowWeather = list.get(1);
		String temp = tomorrowWeather.getLowTemp() + "~" + tomorrowWeather.getHighTemp() + Constants.degree;
		
		content.append("* "+ temp + "\n");
		content.append("* "+ tomorrowWeather.getWeather()+ "\n");
		if(StringUtils.isNotBlank(tomorrowWeather.getWind())){
			content.append("* "+ tomorrowWeather.getWind()+ "\n");
		}
		if(StringUtils.isNotBlank(tomorrowWeather.getIndex_uv())){
			content.append("* 紫外线"+ tomorrowWeather.getIndex_uv()+ "\n");
		}
		if(StringUtils.isNotBlank(tomorrowWeather.getTempChange())){
			content.append("* "+ tomorrowWeather.getTempChange() + "\n");
		}
		
		String xc = tomorrowWeather.getIndex_xc();
		if(StringUtils.isNotBlank(xc)){	
			if(xc.contains("。") && !xc.endsWith("。")){
				xc = xc.substring(xc.lastIndexOf("。")+1, xc.length());
				
			}else{
				xc = xc.substring(xc.lastIndexOf("，")+1, xc.length());
			}
			content.append("* "+ xc + "\n");
		}
		
		for(int i=2; i<4; i++){
			Weather weather = list.get(i);
			if(weather == null){
				break;
			}
			content.append("\n");
			
			content.append(weather.getChinaDate()+"\n");
			String temp1 = weather.getLowTemp() + "~" + weather.getHighTemp() + Constants.degree;
			content.append(temp1 +",  "+ weather.getWeather() + ",  "+ weather.getWind()+"\n");
		}		
		
		return content.toString();
	}
	
	public static String get3DayWeatherStr(List<Weather> list, String cityName) {
		
		StringBuilder content = new StringBuilder();
		
		if(list == null || list.size()==0){
			return "";
		}
		
		content.append("=="+ cityName + " 今日天气=="+ "\n");
		Weather firstOne = list.get(0);
		String temp = firstOne.getLowTemp() + "~" + firstOne.getHighTemp() + Constants.degree;
		
		content.append("* "+ temp + "\n");
		content.append("* "+ firstOne.getWeather()+ "\n");
		content.append("* "+ firstOne.getWind()+ "\n");
		content.append("* 紫外线"+ firstOne.getIndex_uv()+ "\n");
		
		if(StringUtils.isNotBlank(firstOne.getAir_quality())){
			
			String note = Constants.airQualityNote.get(firstOne.getAir_quality());
			if(StringUtils.isNotBlank(note)){
				content.append("* "+ note + "\n");
			}
		}
		
		if(StringUtils.isNotBlank(firstOne.getTempChange())){
			content.append("* "+ firstOne.getTempChange() + "\n");
		}
		
		String xc = firstOne.getIndex_xc();
		if(StringUtils.isNotBlank(xc)){	
			if(xc.contains("。") && !xc.endsWith("。")){
				xc = xc.substring(xc.lastIndexOf("。")+1, xc.length());
				
			}else{
				xc = xc.substring(xc.lastIndexOf("，")+1, xc.length());
			}
            int n;
            if((n=xc.indexOf("注意"))!=-1){
                xc=xc.substring(0,n);
            }
			content.append("* "+ xc + "\n");
		}

		//list.remove(0);
		
		for(int i=1; i<3; i++){
			Weather weather = list.get(i);
			if(weather == null){
				break;
			}
			content.append("\n");
			
			content.append(weather.getChinaDate()+"\n");
			String temp1 = weather.getLowTemp() + "~" + weather.getHighTemp() + Constants.degree;
			content.append(temp1 +",  "+ weather.getWeather() + ",  "+ weather.getWind()+"\n");
		}		
		
		return content.toString();
	}
	
	
	
	private static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
}
